package com.iqiyi.pps.epg.core.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.iqiyi.kiwi.utils.Configuration;
import com.iqiyi.kiwi.utils.HttpClientConnection;
import com.iqiyi.pps.epg.core.model.program.WritePuYuQipuData;
import com.iqiyi.pps.epg.core.utils.puyu.HttpSignatureUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by karkarrotxu on 2015/7/28.
 */
public class ApiPuYuRequestUtil {
    private static Logger logger = LoggerFactory.getLogger(ApiPuYuRequestUtil.class);
    private static final String TEST_QUERY_URL = Configuration.getString("thirdApi.puyu.url");
    private static final String TEST_CLIENTID =  Configuration.getString("thirdApi.puyu.clientId");
    private static final String TEST_KEY = Configuration.getString("thirdApi.puyu.key");
    private static final String HEADER_CHECK_KEY = "CPR-Authentication";

    public static void testExcute() {
        //    String barCode =  "4676A7AE34085168liyang20141210105854";
        // 	String barCode =  "2784A767E75CE974hjjmh20140902144727";

    }

    public static String queryForPuyuBarCode(String barCode) {
        Map<String, Object> parameters = new HashMap<String, Object>();
        parameters.put("ts", System.currentTimeMillis() + "");
        parameters.put("start",  "1");
        parameters.put("pageSize", "10");
        parameters.put("barCode", barCode);
        parameters.put("showPlatformLimits", "0");

        return doQuery(parameters);
    }

    public static String queryForPuyuCprVideoName(String cprVideoName) {
        try {
            cprVideoName = URLEncoder.encode(cprVideoName,"UTF-8");
        } catch (UnsupportedEncodingException e) {
            logger.warn("[ApiPuYuRequestUtil][queryForPuyuCprVideoName]",e);
            return null;
        }
        Map<String, Object> parameters = new HashMap<String, Object>();
        parameters.put("ts", System.currentTimeMillis() + "");
        parameters.put("start",  "1");
        parameters.put("pageSize", "10");
        parameters.put("cprVideoName", cprVideoName  );
        parameters.put("showPlatformLimits", "0");
        return doQuery(parameters);
    }

    private static String doQuery(Map<String, Object> parameters) {
        String headerCode = HttpSignatureUtil.createToken(TEST_CLIENTID, TEST_KEY, parameters);
        Map<String, Object> headers = new HashMap<String, Object>();
        headers.put(HEADER_CHECK_KEY, headerCode);
        logger.info( "headerCode:"+headerCode );
        Long startTime = System.currentTimeMillis();
        HttpClientConnection connection = null;
        String data = null;
        for (int i = 0; i < 3; i++) {
            connection = new HttpClientConnection(TEST_QUERY_URL, HttpClientConnection.GET_METHOD);
            connection.addReqHeader(HEADER_CHECK_KEY,headerCode);
            if(parameters != null){
                connection.setReqParams(parameters);
            }
            connection.setSoTimeout(30000);
            connection.connect();
            logger.info("[HTTP][getMethod][headers:{}][params:{}][status:{}]", new Object[]{ JSON.toJSONString(headers), JSON.toJSONString(parameters),connection.getStatus()});
            if (connection.getStatus() == 200) {
                data = connection.getBody();
                logger.info("[ApiPuYuRequestUtil][doQuery][response:{}]", data);
                return data;
            }
        }
        logger.info("[ApiPuYuRequestUtil][doQuery][cost:{}]", System.currentTimeMillis() - startTime);
        return null;
    }

    public static WritePuYuQipuData decodeForBarCode(String barCode){
        if(barCode == null){
            return null;
        }
        WritePuYuQipuData retValue = null;
        String response =  queryForPuyuBarCode( barCode );
        try{
            JSONObject json = JSONObject.parseObject(response) ;
            JSONArray jsonArray = json.getJSONArray("cprContents");
            if(jsonArray != null &&  jsonArray.size() > 0){
                retValue = new  WritePuYuQipuData();
                retValue.setBarCode( barCode );
                JSONObject element =  jsonArray.getJSONObject(0);
                long startTime =  DateTimeUtil.parseToLong(element.getString("startTime"))  ;
                long endTime = DateTimeUtil.parseToLong(element.getString("endTime"))  ;
                if( startTime == 0 || endTime == 0){
                    return null;
                }
                retValue.setStartTime(startTime );
                retValue.setEndTime(endTime);
                retValue.setCprName(element.getString("cprName"));
                retValue.setContractNumber(  element.getString("contractNumber"));
                retValue.setCprOwnerId(element.getLong("cprOwnerId"));
                retValue.setVideoId( element.getLong("videoId"));
                retValue.setVideoName( element.getString("videoName"));
                retValue.setContractId ( element.getLong("contractId"));
            }
        }catch(Exception e){
            logger.warn("[ApiPuYuRequestUtil][decodePuYu] error puyuResponse:"+response);
            return null;
        }
        return retValue;
    }

    public static void main(String[] args) {
        testExcute();
    }

}
